import ReactDOM from 'react-dom';
import React, { useState } from 'react';
import { Loading } from '@alifd/next';
import mergeWith from 'lodash/mergeWith';
import isArray from 'lodash/isArray';
import { buildComponents, assetBundle, AssetLevel, AssetLoader } from '@alilc/lowcode-utils';
import { injectComponents } from '@alilc/lowcode-plugin-inject';
import { createFetchHandler } from '@alilc/lowcode-datasource-fetch-handler'
import { getProjectSchemaFromLocalStorage, getPackagesFromLocalStorage } from './services/mockService';
import ReactRenderer from '@alilc/lowcode-react-renderer';
import appHelper from './appHelper';
import type { IObject } from './utils/interface';

const getScenarioName = function () {
  if (location.search) {
    return new URLSearchParams(location.search.slice(1)).get('scenarioName') || 'index';
  }
  return 'index';
}

const SamplePreview = () => {
  const [data, setData] = useState({});

  async function init() {
    const scenarioName = getScenarioName();
    const packages = await getPackagesFromLocalStorage(scenarioName);
    const projectSchema = await getProjectSchemaFromLocalStorage(scenarioName);
    console.log(projectSchema, 'projectSchema-----', packages);
    const { componentsMap: componentsMapArray, componentsTree } = projectSchema;
    const componentsMap: any = {};
    componentsMapArray.forEach((component: any) => {
      componentsMap[component.componentName] = component;
    });
    const schema = componentsTree[0];
    console.log(projectSchema, 'projectSchema------------')
    const libraryMap = {};
    const libraryAsset: any[] = [];
    packages.forEach(({ package: _package, library, urls, renderUrls }) => {
      libraryMap[_package] = library;
      if (renderUrls) {
        libraryAsset.push(renderUrls);
      } else if (urls) {
        libraryAsset.push(urls);
      }
    });

    const vendors = [assetBundle(libraryAsset, AssetLevel.Library)];

    // TODO asset may cause pollution
    const assetLoader = new AssetLoader();
    await assetLoader.load(libraryAsset);
    // injectComponents 的使用一般在开发环境做调试注入使用（详细见文档），一般纯净的预览环境是不依赖此插件（即预览渲染态理论上是不需要依赖任何引擎及其相关的插件等资源，PS: 一些 utils 和 types 忽略）
    // The use of injectComponents is generally used for debugging and injection in the development environment (see the documentation for details). The generally destroyed preview environment does not rely on this plug-in.
    // const components = await injectComponents(buildComponents(libraryMap, componentsMap));
    const components = buildComponents(libraryMap, componentsMap);
    // const components = await injectComponents(buildComponents(libraryMap, componentsMap));

    setData({
      schema,
      components,
    });
  }

  // const { schema, components } = data;
  const { schema, components, i18n = {}, projectDataSource = {} } = data as any;

  if (!schema || !components) {
    init();
    return <Loading fullScreen />;
  }

  function customizer(objValue: [], srcValue: []) {
    if (isArray(objValue)) {
      return objValue.concat(srcValue || []);
    }
  }

  // 处理下拉菜单选择
  const handleMenuChange = (event: React.ChangeEvent<{ value: unknown }>) => {
    const url = event.target.value as string;
    if (url) {
      window.location.href = url;
    }
  };
  // 定义select的样式
  const selectStyles = {
    marginTop: '10px', // 根据需要调整
    marginLeft: '10px', // 根据需要调整
    // padding: '8px 16px',
    borderRadius: '4px',
    border: '1px solid #ccc',
    backgroundColor: '#fff',
    fontSize: '12px',
    cursor: 'pointer',
    outline: 'none',
  };
  // 从全局变量中获取select的选项
  const options = (window as any).selectBoxData.map((item: any, index: number) => (
    <option key={index} value={item.url}>{item.label}</option>
  ));

  return (
    <div className="lowcode-plugin-sample-preview" id="previewDivId">
      <select onChange={handleMenuChange} style={selectStyles}>
        <option >菜单</option>
        {options}
      </select>
      <ReactRenderer
        className="lowcode-plugin-sample-preview-content"
        schema={{
          ...schema,
          dataSource: mergeWith(schema.dataSource, projectDataSource, customizer),
        }}
        components={components}
        messages={i18n}
        appHelper={appHelper}

      />
    </div>
  );
};

ReactDOM.render(<SamplePreview />, document.getElementById('ice-container'));
